package com.moss.cloud.common.security.exception;

import com.moss.cloud.common.core.exception.BaseException;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.util.Objects;

/**
 * 微服务全局异常处理
 * @author 瑾年
 * @date 2019/05/23
 */
@Slf4j
@RestControllerAdvice
public class DefaultGlobalExceptionHandlerAdvice {

    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    public Result<?> missingServletRequestParameterException(MissingServletRequestParameterException ex) {
        log.error("缺少servlet请求参数异常:{}", ex.getMessage());
        return Result.fail(SystemErrorType.ARGUMENT_NOT_VALID);
    }

    @ExceptionHandler(value = {MultipartException.class})
    public Result<?> uploadFileLimitException(MultipartException ex) {
        log.error("文件上传大小异常:{}", ex.getMessage());
        return Result.fail(SystemErrorType.UPLOAD_FILE_SIZE_LIMIT);
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result<?> serviceException(MethodArgumentNotValidException ex) {
        log.error("请求参数校验异常:{}", ex.getMessage());
        return Result.fail(SystemErrorType.ARGUMENT_NOT_VALID, Objects.requireNonNull(ex.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(value = {BaseException.class})
    public Result<?> baseException(BaseException ex) {
        log.error("业务处理异常:{}", ex.getErrorType().getMesg());
        if(ex.getErrorType().getCode().equals(SystemErrorType.BUSINESS_ERROR.getCode())){
            return Result.fail(ex.getErrorType(),ex.getMessage());
        }
        return Result.fail(ex.getErrorType());
    }
    @ExceptionHandler(value = {DuplicateKeyException.class})
    public Result<?> duplicateKeyException(DuplicateKeyException ex) {
        log.error("数据库唯一索引冲突:{}", ex.getMessage());
        return Result.fail(SystemErrorType.UNIQUE_ATTRIBUTE);
    }

}